class Lists {
    constructor() {
        this.getDate();
        this.bang();
        //默认页码添加
        this.currentPage = 1;
    }
    //绑定的事件
    bang() {
        //懒加载事件绑定滚动条3
        window.addEventListener('scroll', this.Lazy)
        //通过时间委托,给UL绑定点击事件
        this.$('.sk_bd ul').addEventListener('click', this.checkLogin.bind(this))
        //绑定图片跳转详情
        // this.$('.sk_bd ul').addEventListener('click', this.xq.bind(this))
    }
    //获取数据
    async getDate(page = 1) {
        // console.log('测试测试');
        //发送ajax请求
        let goodsData = await axios.get('http://localhost:8888/goods/list?current=' + page);
        // console.log(goodsData);获取了数据然后进行拼接追加到页面中
        //拿到网络状态和接口返回数据
        let status = goodsData.status;
        let data = goodsData.data;
        // console.log(status,data);
        //判断请求状态,获取数据,如果状态不对,抛出错误
        if (status != 200 && data.code != 1) throw new Error('获取数据失败')
        //将data.list的数据通过循环追加
        let html = ''
        data.list.forEach(goods => {
            console.log(goods); 
            //拼接模板,替换变量
            html += `<li class="sk_goods" data-id="${goods.goods_id}">
            <a href="#none" class="img_big_logo">
                <img src="${goods.img_big_logo}" alt="">
            </a>
            <h5 class="sk_goods_title">${goods.title}</h5>
            <p class="sk_goods_price">
                <em>${goods.current_price}</em>
                <del>${goods.price}</del>
            </p>
            <div class="sk_goods_progress">
                已售
                <i>${goods.sale_type}</i>
                <div class="bar">
                    <div class="bar_in"></div>
                </div>
                剩余
                <em>${goods.goods_number}</em>件
            </div>
            <a href="#none" class="sk_goods_buy" >立即抢购</a>
        </li>`
        });
        //测试拼加是否成功,追加到页面当中
        // console.log(html);
        // console.log(this.$('.sk_bd ul'));
        this.$('.sk_bd ul').innerHTML += html;
        this.liObj()
    }


    //添加页面懒加载功能奥
    Lazy = () => {
        //滚动条高度
        let scrollTop = document.documentElement.scrollTop;
        // console.log(scrollTop);
        //显示区高度
        let clientTop = document.documentElement.clientHeight;
        // console.log(clientTop);
        //内容高度
        let content = this.$('.sk_container')
        // console.log(content);
        let contentTop = content.offsetHeight
        // console.log(contentTop);
        //验证
        // let contentTop=this.$('.sk_container').offsetHeight;
        // console.log(contentTop);
        //滚动条高度大于实际内容高度时,增加数据
        if (scrollTop + clientTop > (clientTop + 450)) {
            // console.log('test');
            //用节流防抖,避免不停触发
            if (this.lock) return;
            this.lock = true;
            //假如定时器,规定一个时间开锁一次,避免不停触发条件加载数据
            setTimeout(() => {
                this.lock = false;
            }, 1000);
            //超出后自动页面数加一传入下一组数据
            this.getDate(++this.currentPage)
        }
    }
    //点击添加让产品假如到购物车中
    checkLogin(event) {
        // console.log(this);
        if (event.target.nodeName != 'A' || event.target.className != 'sk_goods_buy') return;
        // console.log(event.target);
        //判断用户是否有TOKEN值
        let token = localStorage.getItem('token');
        // console.log(token);
        //如果token为null 去登录的界面进行登录操作
        if (!token) location.assign('./login.html?ReturnUrl=./list.html ');
        //如果已经登录,添加进入购物车
        let goodsId = event.target.parentNode.dataset.id
        // console.log(goodsId);
        let userId = localStorage.getItem('user_id')
        // console.log(goodsId,userId);
        this.addBox(goodsId, userId);
    }
    //如果有token进入购物车页面
    addBox(gId, uId) {
        //发送购物车请求
        const AUTH_TOKEN = localStorage.getItem('token');
        axios.defaults.headers.common['authorization'] = AUTH_TOKEN;
        axios.defaults.headers['Content-type'] = 'application/x-www-form-urlencoded';
        let param = `id=${uId}&goodsId=${gId}`;
        axios.post(' http://localhost:8888/cart/add', param).then(res => {
            // console.log(res);
            let data = res.data;
            let status = res.status;
            // console.log(data,status);
            if (status == 200 && data.code == 1) {
                
                // 引入Layer
                layer.open({
                    title:'这就添加奥' ,
                    content:'去购物车看看有多贵!',
                    btn:['买不起','加入购物车','看放大镜'],
                    btn2:function(index,layero){
                       location.assign('./cart.html')
                    },
                    btn3:function(){
                        location.assign('./detail.html');
                        checkLogin(goodsId)
                    }
                 });
            }else if(status == 200 && (data.code == 401||data.code==0)){
                localStorage.removeItem('token');
                localStorage.removeItem('user_id')
                location.assign('./login.html?ReturnUrl=./list.html');
            }
            else{
                layer.open({
                    title:'这就G了' ,
                    content:'去购物车看看有多贵!',
                    btn:['买不起','使劲买'],
                    time:3000
                 });
            }
        })
    }
    //跳转详情
    // xq(event){
    //     if (event.target.nodeName != 'A' || event.target.className != 'img_big_logo') return;
    //     console.log(this);
    //     console.log(event.target);
    // }
    liObj(){
        let ulsObj = this.$('.sk_bd ul')
        let liObj = ulsObj.querySelectorAll('li .img_big_logo')
        // console.log(liObj)
        liObj.forEach(li=>{
            //点击之后跳转到列表详情页
            // li.onclick = this.liObjClick
            li.onclick = function(){
                console.log('商品ID')
                 let goodsId =this.parentNode.dataset.id
                 console.log(this.goodsId)
                 //把点击的商品的ID传过去
                 localStorage.setItem("goodId",goodsId)
                 
                 location.assign('./detail.html?goodsID='+goodsId)
                 
            }
        })
    }
    //封装获取节点的方法
    $(ele) {
        let res = document.querySelectorAll(ele);
        return res.length == 1 ? res[0] : res
    }
}
new Lists;
        // //引入Layer
        // layer.open({
        //     title:'这就添加奥' ,
        //     content:'去购物车看看有多贵!',
        //     btn:['买不起','使劲买'],
        //     btn2:function(index,layer){
        //         console.log('succsess');
        //     }
        //  });